#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define KB_SIZE 1024
#define MB_SIZE (1024 * KB_SIZE)
#define GB_SIZE (1024 * MB_SIZE)
#define BUF_4K (4 * KB_SIZE)

void show_cache_buffer_info()
{
    system("free -m");
    system("grep -E 'Buffers|Cached' /proc/meminfo");
}

void help()
{
    char* help_str = "\
    默认 正常读文件 \n\
    1 n NOREUSE \n\
    2 d DONTNEED\n";
    printf("%s", help_str);
}

int main(int argc, char* argv[])
{
    // 0.清空系统 cache/buffer
    system("sync; echo 3 > /proc/sys/vm/drop_caches");
    show_cache_buffer_info();

    // 1.创建文件
    int fd = open("test.txt", O_WRONLY | O_CREAT, 0644);
    if (fd < 0)
    {
        perror("open");
        exit(1);
    }

    // 2.写文件
    char buf[BUF_4K];
    int count = MB_SIZE * 512;
    while (count)
    {
        write(fd, buf, BUF_4K);
        count -= BUF_4K;
    }

    // 3.释放 缓存
    fsync(fd);      // fsync将写数据落盘，这样才能确保 page cache全部释放成功
    if (argc == 2)
    {
        char opt = *argv[1];
        if (opt == '1' || opt == 'n')
            posix_fadvise(fd, 0, 0, POSIX_FADV_NOREUSE);
        if (opt == '2' || opt == 'd')
            posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
    }

    // 4.关闭文件
    close(fd);
    show_cache_buffer_info();
}
/* 测试1: ./5_写文件_是否会生成buffer_cache.out
              total        used        free      shared  buff/cache   available
Mem:           7901        1056        6419           7         425        6600
Swap:          2047           0        2047
Buffers:            8708 kB
Cached:           381292 kB
SwapCached:            0 kB

              total        used        free      shared  buff/cache   available
Mem:           7901        1054        5897           7         950        6596
Swap:          2047           0        2047
Buffers:            8720 kB
Cached:           905556 kB
SwapCached:            0 kB
 */

 /* 测试2: ./5_写文件_是否会生成buffer_cache.out 2
               total        used        free      shared  buff/cache   available
 Mem:           7901        1066        6499           7         336        6590
 Swap:          2047           0        2047
 Buffers:            2524 kB
 Cached:           297488 kB
 SwapCached:            0 kB

               total        used        free      shared  buff/cache   available
 Mem:           7901        1067        6496           7         337        6589
 Swap:          2047           0        2047
 Buffers:            3300 kB
 Cached:           297800 kB
 SwapCached:            0 kB


  */

  /* 测试结论:
  1. 写文件也会造成 系统cache/buffer 增加
  2. 如果写文件之后, 确认不适用, 可以使用 posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); 是否系统cache
   */